const API = require('../../pages/api/index')
const {
  typeJson
} = require('../../utils/typejson')
let prolist = wx.getStorageSync('prolist') == '' ? wx.getStorageSync('prolist') : JSON.parse(wx.getStorageSync('prolist'))
const {
  get,
  post
} = require('../../request/index')


Page({

  /**
   * 页面的初始数据
   */
  data: {
    pulldown: "",
    pullup: 2,
    addButton: true,
    show: false,
    prolist: wx.getStorageSync('prolist') == '' ? wx.getStorageSync('prolist') : JSON.parse(wx.getStorageSync('prolist')),
    mainActiveIndex: 0,
    activeId: [],
    activeIdPopup: [],
    max: 1,
    deptTreeList: [],
    wuanpoplist: [],
    flowDetails: [],
    usingUnit: [],
    wuanlist: [],
    names: null, //姓名集合以“，”分割传进来，前端调查询人员的接口获取姓名后填充到该字段
    userId: null, //int类型 申请人ID ,即当前用户id
    applyUseId: null, //int类型 申请人ID ,即当前用户id
    cardType: null, // 证件类型（前端传固定值,1=身份证件，2护照，工作证，执行公务证，其他）
    beginTime: null, //计划开始时间
    endTime: null, //计划离开时间
    contenct: null, // 事由
    inTime: null, // 实际进入时间
    outTime: null, //实际离开时间
    title: null, //标题
    seletType: null,
    bgColor: "#ccc",
    klit: [],
    opId: null,
    steps: [{
        text: '步骤一',
        desc: '数据录入',
      },
      {
        text: '步骤二',
        desc: '选择审批人',
      },
      {
        text: '步骤三',
        desc: '发起审核',
      }
    ],
    names: "",
    jsonType: [{
        label: "身份证件",
        value: 1
      },
      {
        label: "护照",
        value: 2
      },
      {
        label: "工作证",
        value: 3
      },
      {
        label: "执行公务证",
        value: 4
      },
      {
        label: "其他",
        value: 5
      }
    ],
    people: []
  },
  onChangegroup(event) {

    this.setData({
      people: event.detail,
    });
  },
  changeTime1(e) {
    this.setData({
      beginTime: e.detail
    })
  },
  changeTime2(e) {
    this.setData({
      endTime: e.detail
    })
  },
  bindinput(e) {
    console.log(e);
    this.setData({
      [e.currentTarget.dataset.num]: e.detail.value
    })
  },
  changeSelect(e) {
    this.setData({
      seletType: e.detail
    })
  },
  selent() {
    this.setData({
      show1: true
    })
  },
  onClose() {
    this.setData({
      show: false,
      show1: false,
    });
  },
  changeUpint(e) {
    this.setData({
      designForm: e.detail,
    });
  },
  onChange(event) {

    this.setData({
      usingUnit: event.detail,
    });
  },
  submit() {
 
    let {
      names, //姓名集合以“，”分割传进来，前端调查询人员的接口获取姓名后填充到该字段
      cardType, // 证件类型（前端传固定值,1=身份证件，2护照，工作证，执行公务证，其他）
      beginTime, //计划开始时间
      endTime, //计划离开时间
      contenct, // 事由
      inTime, // 实际进入时间
      outTime, //实际离开时间
      title, //标题
      prolist,
      flowDetails,
      seletType

    } = this.data;
    flowDetails.forEach((item, index) => {
      item.sort = index + 1;
      delete item.name;
    })

    post('/app/balstLibrary', {
      title, //标题
      names, //姓名集合以“，”分割传进来，前端调查询人员的接口获取姓名后填充到该字段
      applyUseId: prolist.userId, //int类型 申请人ID ,即当前用户id
      cardType:this.selType(seletType), // 证件类型（前端传固定值,1=身份证件，2护照，工作证，执行公务证，其他）
      beginTime, //计划开始时间
      endTime, //计划离开时间
      contenct, // 事由
      flowDetails, //审核人列表
      type: 2,
      userId: prolist.userId //用户id

    }).then(res => {

      if (res.code == 200) {

        wx.showToast({
          title: '提交成功',
          duration: 3000,
          icon: 'success',
          mask: true
        })
        wx.navigateTo({
          url: '/pages/dangerConfirm/dangerConfirm',
        })
      }
    })

  },
  selType(v) {
    let str = ""
    switch (v) {
      case 1:
        str = "身份证件"
        break;
      case 2:
        str = "护照"
        break;
      case 3:
        str = "工作证"
        break;
      case 4:
        str = "执行公务证"
        break;
      case 5:
        str = "其他"
        break;

      default:
        break;
    }
    return str
  },
  nextStep() {
    this.setData({
      show: true,
      flowDetails: [],
      wuanpoplist: []
    });

  },
  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },
  onChangeInput(e) {


    this.setData({
      [e.target.dataset.lable]: e.detail
    })
  },

  onClickNav({
    detail = {}
  }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    });
  },

  onClickItem({
    detail = {}
  }) {
    console.log(detail);
    const activeId = this.data.activeId === detail.id ? null : detail.id;
    this.setData({
      activeId,
      usingUnit: [],
      show1: false,
      names: detail.text
    });
    this.postbalstWork(activeId)

  },

  cross(e) {
    let {
      flowDetails
    } = this.data
    console.log(e.currentTarget.dataset.user);
    flowDetails.map(((item, index) => {
      if (item.auditUserId == e.currentTarget.dataset.user) {
        flowDetails.splice(index, 1)
      }
    }))
    this.setData({
      flowDetails: flowDetails
    })
  },
  edit(e) {

    let {
      flowDetails
    } = this.data;
    let {
      userId,
      nickName
    } = e.target.dataset.item


    let flag = true;
    if (flowDetails.length != 0) {

      flowDetails.forEach(item => {
        console.log(item);
        if (item.auditUserId == userId) {
          flag = false
        }
      });


    }
    console.log(flag);

    if (flag) {
      let obj = {
        auditUserId: userId,
        name: nickName,
      };
      let list = [];

      list.push(obj);


      this.setData({
        flowDetails: flowDetails.concat(list),

      })
    }





  },
  onClickPopup({
    detail = {}
  }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    });
  },
  onClickItemPopup({
    detail = {}
  }) {
    console.log(detail);
    const activeIdPopup = this.data.activeIdPopup === detail.id ? null : detail.id;
    console.log(activeIdPopup);
    this.setData({
      activeIdPopup,

    });
    this.postbalstWork(activeIdPopup);
  },
  async postbalstWork(activeId) {
    let res = await get(`/system/user/list?deptId=${activeId}&peopleType=1&pageNum=1&pageSize=999`)
    if (res.code == 200) {
      this.setData({
        wuanlist: res.rows,
        wuanpoplist: res.rows
      })
    }
  },






  /**
   * 生命周期函数--监听页面加载
   */


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getDeptTree();
  },

  async getDeptTree() {
    let res = await get('/system/user/deptTree');

    if (res.code == 200) {
      let newJsonParam = JSON.parse(JSON.stringify(res.data).replace(/label/g, "text"));
      this.setData({
        deptTreeList: newJsonParam
      })
    }
  },




  canvasChang(e) {
    console.log(e.detail);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      pullup: this.data.pullup + 1
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})